package org.zoomdev.zoom.rpc.utils;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public abstract class MessageDecoder extends ByteToMessageDecoder {
    public static final int HEADER_SIZE = 12;
    public static final byte[] EMPTY = new byte[0];

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf readBuffer, List<Object> list) throws Exception {
        if (readBuffer.readableBytes() < HEADER_SIZE) {
            return;
        }

        int len = readBuffer.getInt(1);
        if (readBuffer.readableBytes() >= len + HEADER_SIZE) {
            byte head = readBuffer.readByte();
            if (head != (byte) 0xcc) {
                ctx.close();
                return;
            }
            readBuffer.readInt();
            int id = readBuffer.readInt();
            short func = readBuffer.readShort();
            byte[] bytes;
            if (len > 0) {
                bytes = new byte[len];
                readBuffer.readBytes(bytes);
            } else {
                bytes = EMPTY;
            }
            byte tail = readBuffer.readByte();
            if (tail != (byte) 0xca) {
                ctx.close();
                return;
            }
            Object ret = createObject(id, func, bytes);
            if (ret != null) {
                list.add(ret);
            }
        }
    }

    protected abstract Object createObject(int id, short func, byte[] bytes);
}
